package com.af.system.servlet.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

/**
 * @author : zhenyun.su
 * @comment : 为所有访问x3微服务的请求添加token
 * @since : 2022/9/6
 */

public class RestTemplateRequestInterceptor implements ClientHttpRequestInterceptor {
    private static final Logger log = LoggerFactory.getLogger(RestTemplateRequestInterceptor.class);
    public static final String TOKEN_KEY="Authorization";

    private String tokenValue;

    public RestTemplateRequestInterceptor(String tokenValue) {
        this.tokenValue = tokenValue;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        HttpHeaders headers = request.getHeaders();
        headers.add(TOKEN_KEY, tokenValue);
        log.debug("RestTemplateRequestInterceptor, token: {}", tokenValue);
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        return execution.execute(request, body);
    }

    public void setTokenValue(String tokenValue) {
        this.tokenValue = tokenValue;
    }
}
